
#include "espconfig.h"

#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#define DOWNLOAD_PACKET_SIZE 1024
#elif defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#include <AsyncTCP.h>
#define DOWNLOAD_PACKET_SIZE 2048
#endif
#include "httpserver.h"
#include "espsettings.h"

#include <ESPAsyncWebServer.h>
#include <AsyncElegantOTA.h>

// #include "../websocket/websocket_server.h"

bool HTTP_Server::_started = false;
uint16_t HTTP_Server::_port = 0;
WEBSERVER *_webserver;
uint8_t HTTP_Server::_upload_status = UPLOAD_STATUS_NONE;

void HTTP_Server::init_handlers()
{
    _webserver->on("/", HTTP_ANY, [](AsyncWebServerRequest *request)
                   { handle_root(request); });
    _webserver->on("/state", HTTP_ANY, [](AsyncWebServerRequest *request)
                   { handle_state(request); });
    _webserver->on("/test", HTTP_GET, [](AsyncWebServerRequest *request)
                  { request->send(200, "text/plain", "Hi! This is a sample response."); });
}

void HTTP_Server::pushError(int code, const char *st, uint16_t web_error, uint16_t timeout)
{
    // log_debug("%s:%d",st,web_error);
    // if (websocket_terminal_server.started() && st) {
    //     String s = "ERROR:" + String(code) + ":";
    //     s+=st;
    //     websocket_terminal_server.pushMSG(websocket_terminal_server.get_currentID(), s.c_str());
    //     if (web_error != 0) {
    //         if (_webserver) {
    //             if (_webserver->client().available() > 0) {
    //                 _webserver->send (web_error, "text/xml", st);
    //             }
    //         }
    //     }
    //     uint32_t t = millis();
    //     while (millis() - t < timeout) {
    //         websocket_terminal_server.handle();
    //         Hal::wait(10);
    //     }
    // }
}

bool HTTP_Server::begin()
{
    bool no_error = true;
    end();
    _port = 80;
    _webserver = new WEBSERVER(_port);
    if (!_webserver)
    {
        return false;
    }

    HTTP_Server::init_handlers();

    // // const char *headerkeys[] = {"Content-Length"};
    // // size_t headerkeyssize = sizeof(headerkeys) / sizeof(char *);
    // // _webserver->collectHeaders(headerkeys, headerkeyssize);
    _webserver->begin();
    AsyncElegantOTA.begin(_webserver); // Start AsyncElegantOTA
    // _started = no_error;
    return no_error;
}

void HTTP_Server::end()
{
    _started = false;
    _upload_status = UPLOAD_STATUS_NONE;
    if (_webserver)
    {
        _webserver->end();
        delete _webserver;
        _webserver = NULL;
    }
}

void HTTP_Server::handle()
{
    // if (_started)
    // {
    //     if (_webserver)
    //     {
    //         // _webserver->handleClient();
    //     }
    // }
}